<template>
  <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单单号" prop="billId">
            <el-input v-model="dataForm.billId">
              <el-button slot="append" @click="selectOrderDialog">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购类型" prop="ctgId">
            <el-select v-model="dataForm.ctgId" @change="ctgChangeHandle">
              <el-option v-for="item in ctgOptions" :key="item.value" :value="item.value" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造商" prop="supplyName">
            <el-input v-model="dataForm.supplyName">
              <el-button slot="append" @click="selectSupplyDialog">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收入仓位" prop="inStockId">
            <el-select v-model="dataForm.inStockId">
              <el-option v-for="item in stockOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8"></el-col>
        <el-col :span="8"></el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input v-model="dataForm.memo" type="textarea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label-width="0">
            <el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button>
            <el-button type="primary" @click="addGoodsByBivariate">二维表添加商品</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item style="float: right;">
            <el-button type="danger" @click="delTableData">删除</el-button>
            <el-button type="info" @click="delTableData">清空</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 采购商品列表 -->
      <ctg-table ref="ctgTable" @refreshData="handleSelectionChange" :ctgId="dataForm.ctgId" :dataList="dataList" :dataListLoading="dataListLoading" :selectList="selectList" @quantityChange="quantityChangeHandle"></ctg-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>确定</el-button>
      <el-switch v-if="permissions.eims_inventory_audit" v-model="dataForm.inveStatus" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
    <!-- 弹窗，查询选择制造商 -->
    <supply-search v-if="supplySearchVisible" ref="supplySearch" @refreshData="checkSupply"></supply-search>
    <!-- 弹窗，查询选择商品 -->
    <single-search v-if="singleSearchVisible" ref="singleSearch" @updateForm="checkGoods"></single-search>
    <!-- 弹窗，二维表添加商品 -->
    <bivariate-table v-if="bivariateVisible" ref="bivariateDialog" @refreshData="getGoodsData"></bivariate-table>
    <!-- 弹窗，采购订单列表 -->
    <search-order v-if="orderVisible" ref="orderDialog" @refreshData="getOrderData"></search-order>
  </el-dialog>
</template>

<script>
  import {filterParams} from '@/util/tools'
  import { receiveGoodsGetObj, receiveGoodsAddObj, receiveGoodsPutObj } from '@/api/eims/purchase/receive-goods'
  import { fetchCtgList } from '@/api/eims/ctg'
  import { getSupplyObj } from '@/api/eims/supply'
  import { fetchStockList, getStockInfo,getStockList,getStockByDeptTypes } from '@/api/eims/stock'
  import SupplySearch from '@/components/business/SearchSupply'
  import SingleSearch from './goodsSearchSingle'
  import CtgTable from '@/components/business/ctg-table'
  import BivariateTable from '@/components/business/BivariateTable'
  import SearchOrder from './PurchaseOrder'
  import { mapGetters } from 'vuex'
  export default {
    data() {
      return {
				ischeck: false,
        visible: false,
        title: '',
        dataForm: {
          id: 0,
          inStockId: '',
          outStockId: '',
          supplyId: '',
          supplyName: '',
          ctgId: '',
          memo: '',
          inveStatus: '0',
          detailList: []
        },
        ctgOptions: [],
        stockOptions: [],
        dataRule: {
          inStockId: [{ required: true, message: '入库仓库id不能为空', trigger: 'blur' }],
          outStockId: [{ required: true, message: '出库仓库id不能为空', trigger: 'blur' }],
          supplyName: [{ required: true, message: '制造商不能为空', trigger: 'blur' }],
          ctgId: [{ required: true, message: '商品类别id不能为空', trigger: 'blur' }]
        },
        supplySearchVisible: false,
        singleSearchVisible: false,
        bivariateVisible: false,
        dataList: [],
        dataListLoading: false,
        selectList: [],
        orderVisible: false,
      }
    },
    computed: {
        ...mapGetters(['bizData','permissions','userInfo'])
    },
    components: {
      SupplySearch,
      SingleSearch,
      CtgTable,
      BivariateTable,
      SearchOrder
    },
    methods: {
      init(data) {
        this.dataForm.id = data.id || 0
        this.type = data.type
        if(this.type == '4'){
          if(this.dataForm.id){
            this.title = '隐形采购收货更新'
          }else{
            this.title = '隐形采购收货新增'
          }
        }else{
          if(this.dataForm.id){
            this.title = '采购收货更新'
          }else{
            this.title = '采购收货新增'
          }
        }
        this.visible = true
        this.getStockByDeptId()
        this.getStockList()
        this.getGoodsCtgList()
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            receiveGoodsGetObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = this.dataForm.detailList
                if(this.dataList.length){
                  this.dataList.forEach((item,index) => {
                    item.name = item.goodsName
                    item.code = item.goodsCode
                    if(item.invalidTime) {
                      this.$set(this.dataList[index],'invalidTimeStr',item.invalidTime.substring(0,10))
                    }
                  })
                }
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      //  打开采购订单选择
      selectOrderDialog() {
        this.orderVisible = true
        this.$nextTick(() => {
          this.$refs.orderDialog.init()
        })
      },
      //  获取采购订单信息
      getOrderData(data) {
        this.dataForm.billId = data.billId
        this.dataForm.ctgId = data.ctgId
        this.dataForm.supplyId = data.supplyId
        this.dataForm.supplyName = data.supplyName
        let dataList = data.list
        dataList.forEach(item => {
          item.code = item.goodsCode
          item.name = item.goodsName
          item.quantity = item.applyQuantity
        	if(item.ctgId == 4 || item.ctgId == 5){
        		item.goodsBarcode = item.goodsCode.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr .replace(/[\ |\-]/g,"")).substring(2,10) : '0000000') + 'A0'
        	}else{
            item.goodsBarcode = item.goodsCode.replace(/[\ |\.]/g,"") + '00000000'
          }
        })
        this.dataList = JSON.parse( JSON.stringify(dataList) )
        let list = []
        dataList.forEach(item => {
          item.goodsId = item.id
          item.code = item.goodsCode
          item.name = item.goodsName
          item.quantity = item.applyQuantity
          list.push(item)
        })
        this.dataForm.detailList = list
      },
      // 打开选择制造商弹窗
      selectSupplyDialog() {
        if(this.dataForm.ctgId){
          let data = {ctgId: this.dataForm.ctgId}
          this.supplySearchVisible = true
          this.$nextTick(() => {
            this.$refs.supplySearch.init(data)
          })
        }else {
          this.$message.warning('请选择采购类别')
        }

      },
      ctgChangeHandle(val){
        this.dataForm.supplyId = ''
        this.dataForm.supplyName = ''
        this.dataList = []
        this.dataForm.detailList = []
        this.ctgOptions.forEach(item => {
          if(item.value == val){
            this.dataForm.ctgName = item.name
          }
        })
      },
      // 打开选择商品弹窗
      addGoodsBySingle() {
        if(this.dataForm.ctgId && this.dataForm.supplyId){
          let params = {ctgId:this.dataForm.ctgId,supplyId:this.dataForm.supplyId,ctgName: this.dataForm.ctgName,supplyName: this.dataForm.supplyName}
          let data = {params: params,data: this.dataList,disable: true}
          this.singleSearchVisible = true
          this.$nextTick(() => {
            this.$refs.singleSearch.init(data)
          })
        }else{
          if(!this.dataForm.ctgId){
            this.$message.warning('请选择采购类型')
            return
          }
          if(!this.dataForm.supplyId){
            this.$message.warning('请选择制造商')
            return
          }
        }
      },
      //  二维表添加商品
      addGoodsByBivariate() {
        if(this.dataForm.ctgId != 3 && this.dataForm.ctgId != 4){
          this.$message.warning('请选择镜片商品')
          return false
        }
        if(!this.dataForm.supplyId){
          this.$message.warning('请选择制造商')
          return false
        }
        let data = {
          ctgId: this.dataForm.ctgId,
          ctgName: this.dataForm.ctgName,
          supplyId: this.dataForm.supplyId,
          supplyName: this.dataForm.supplyName,
          list: this.dataList
        }
        this.bivariateVisible = true
        this.$nextTick(() => {
          this.$refs.bivariateDialog.init(data)
        })
      },
      checkSupply(data) {
        this.dataForm.supplyId = data.id
        this.dataForm.supplyName = data.name
      },
      checkGoods(data) {
				if(data) {
					data.forEach(item => {
						if(item.ctgId == 4 || item.ctgId == 5){
							item.goodsBarcode = item.code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr .replace(/[\ |\-]/g,"")).substring(2,10) : '0000000') + 'A0'
						}else{
              item.goodsBarcode = item.code.replace(/[\ |\.]/g,"") + '00000000'
            }
					})
        }
        this.dataList = JSON.parse( JSON.stringify(data) )
        let list = []
        data.forEach(item => {
          list.push(item)
        })
        this.dataForm.detailList = list
      },
      //   二维表商品
      getGoodsData(data){
        this.dataList = JSON.parse( JSON.stringify(data) )
        let list = []
        data.forEach(item => {
          list.push(item)
        })
        this.dataForm.detailList = list
      },
      // 商品选择
      handleSelectionChange(val) {
        this.selectList = val
      },
      quantityChangeHandle(val){
        this.dataList.forEach((item,index) => {
          this.$set(this.dataForm.detailList[index],'quantity',item.quantity)
        })
      },
      // 删除选中商品
      delTableData() {
        let list = JSON.parse(JSON.stringify(this.dataList))
        let detailList = JSON.parse(JSON.stringify(this.dataForm.detailList))
        this.selectList.forEach((item,index) => {
          for(let i = 0; i < list.length; i++){
            if(JSON.stringify(list[i]) == JSON.stringify(item)){
              list.splice(i,1)
              detailList.splice(i,1)
            }
          }
          this.selectList = []
        })
        this.dataList = [...list]
        this.dataForm.detailList = [...detailList]
      },
      // 表单提交
      dataFormSubmit() {
				this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            for(let i = 0; i < this.dataList.length;i++){
              if(!this.dataList[i].quantity){
                this.$message.error('请填写采购数量')
								this.ischeck = false
                return false
              }
            }
            this.dataForm.detailList = [...this.dataList]
            // this.dataList.forEach((item,index) => {
            //   this.dataForm.detailList[index].quantity = item.quantity
            //   this.dataForm.detailList[index].invalidTimeStr = item.invalidTimeStr
            //   this.dataForm.detailList[index].batch = item.batch
            //   this.dataForm.detailList[index].registerNum = item.registerNum
            //   this.dataForm.detailList[index].barcode = item.barcode
            // })

            this.dataForm.detailList.forEach(item => {
              item = filterParams(item)
            })
            if (this.dataForm.id) {
              receiveGoodsPutObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            } else {
              receiveGoodsAddObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
								this.ischeck = false
							})
            }
          }else{
						this.ischeck = false
					}
        })
      },
      // 获取商品类别列表
      getGoodsCtgList() {
        fetchCtgList().then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data.records
            let list = []
            resultData.forEach(item => {
              if(this.type == 4 || this.type == 5){
                if(item.id == 4 || item.id == 5){
                  list.push({value:item.id,name:item.name})
                }
              }else{
                if(item.id != 4 && item.id != 5){
                  list.push({value:item.id,name:item.name})
                }
              }
            })
            this.ctgOptions = list
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取仓位列表
      getStockList() {
        var data ={
          stockTypes : [1]
        }
        getStockByDeptTypes(data).then(response => {
          if(response.data.code == '0'){
            this.stockOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getStockByDeptId(){
        getStockInfo(this.userInfo.lessDeptId).then(response => {
          if(response.data.code == '0'){
            this.dataForm.inStockId = response.data.data[0].id
          }else{
            this.$message.error(response.data.msg)
          }
        })
      }
    }
  }
</script>
